load("@rules_rust//cargo:defs.bzl", "cargo_build_script")
load("@rules_rust//rust:defs.bzl", "rust_test")

# generate a file
genrule(
    name = "data_generator",
    outs = ["generated.data"],
    cmd = "echo hello > $@",
)

_data = [
    # we should be able to read non-generated source/data files
    "source.file",
    # and generated files as well
    "generated.data",
    # we should also be able to access external binaries
    # such as protoc.
    "@com_google_protobuf//:protoc",
]

cargo_build_script(
    name = "build",
    srcs = ["build.rs"],
    build_script_env = {
        "GENERATED_DATA": "$(location generated.data)",
        "SOME_TOOL": "$(execpath @com_google_protobuf//:protoc)",
        # both execpath and location should work
        "SOURCE_FILE": "$(execpath source.file)",
    },
    data = _data,
)

rust_test(
    name = "test",
    srcs = [
        "main.rs",
    ],
    data = _data,
    edition = "2018",
    rustc_env = {
        "GENERATED_DATA_ABS": "$(execpath generated.data)",
        "GENERATED_DATA_ROOT": "$(rootpath generated.data)",
        "SOME_TOOL": "$(rootpath @com_google_protobuf//:protoc)",
        "SOURCE_FILE": "$(rootpath source.file)",
    },
    deps = [
        ":build",
    ],
)
